let deviceId;

$(function () {
    initLayUI(function () {
        initButtons();
    })
});

function initLayUI(cb) {
    layui.use(['layer'], function () {
        // 唯一标识
        deviceId = Math.uuid();
        // 图形验证码
        $("#loginCaptcha").attr("src", ServerURL + "/validate/code/" + deviceId);

        cb();
    });
}

function initButtons() {
    $('#loginCaptcha').click(function () {
        deviceId = Math.uuid();
        this.src = ServerURL + "/validate/code/" + deviceId;
    });

    $("#login").click(function () {
        let loginAccount = $("#loginAccount").val();
        let password = $("#password").val();
        let validCode = $("#validCode").val();
        if (isEmpty(loginAccount)) {
            layerUtil.error("账号不能为空");
            return false;
        }
        if (isEmpty(password)) {
            layerUtil.error("密码不能为空");
            return false;
        }
        if (isEmpty(validCode)) {
            layerUtil.error("验证码不能为空");
            return false;
        }
        let loadingIndex = layerUtil.loading(1);
        ajaxUtil.post({
            loginAccount: loginAccount,
            password: password,
            validCode: validCode,
            deviceId: deviceId
        }, "/login", function (res) {
            layerUtil.closeLayer(loadingIndex);
            if (res.code === 200) {
                putTempData('userInfo', res.data);
                tokenUtil.setToken(res.data.token);
                layerUtil.msg({
                    icon: 1,
                    msg: '登录成功',
                    time: 1000
                }, function () {
                    location.href = "home.html";
                });
            } else {
                layerUtil.error(res.msg);
                $("#loginCaptcha").click();
            }
        })
    });

    document.onkeydown = function (event) {
        if (event.key === "Enter") {
            $("#login").click();
        }
    };

}
